package com.it.controller;

import cn.dev33.satoken.util.SaResult;
import com.github.pagehelper.PageInfo;
import com.it.annotation.SystemLog;
import com.it.bean.Quartz;
import com.it.page.PageImpl;
import com.it.page.PageQuery;
import com.it.service.QuartzService;
import lombok.RequiredArgsConstructor;
import org.quartz.SchedulerException;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

/**
 * @author TBH
 * @date 2025-05-19 15:33:42
 * @desc
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/quartz")
public class QuartzController {

    private final QuartzService quartzService;

    @PostMapping("/page")
    @Cacheable(cacheNames = "quartz", key = "T(java.util.Objects).hash(#pageQuery.page, #pageQuery.pageSize, #pageQuery.queryBody)")
    public SaResult page(@RequestBody PageQuery<Quartz> pageQuery) {
        PageInfo<Quartz> pageInfo = quartzService.page(pageQuery);
        return SaResult.data(PageImpl.of(pageInfo));
    }

    @PostMapping("/save")
    @SystemLog(value = "定时任务", method = "新增修改")
    @CacheEvict(cacheNames = "quartz", allEntries = true)
    public SaResult save(@RequestBody Quartz quartz) throws SchedulerException {
        quartzService.save(quartz);
        return SaResult.ok();
    }

    @PostMapping("/delete/{id}")
    @SystemLog(value = "定时任务", method = "数据删除")
    @CacheEvict(cacheNames = "quartz", allEntries = true)
    public SaResult delete(@PathVariable("id") Long id) {
        quartzService.delete(id);
        return SaResult.ok();
    }

    @PostMapping("/pause/{id}")
    @SystemLog(value = "定时任务", method = "任务停止")
    @CacheEvict(cacheNames = "quartz", allEntries = true)
    public SaResult pause(@PathVariable("id") Long id) throws SchedulerException {
        quartzService.pause(id);
        return SaResult.ok();
    }

    @PostMapping("/resume/{id}")
    @SystemLog(value = "定时任务", method = "任务重启")
    @CacheEvict(cacheNames = "quartz", allEntries = true)
    public SaResult resume(@PathVariable("id") Long id) {
        quartzService.resume(id);
        return SaResult.ok();
    }

    @PostMapping("/execute/{id}")
    @SystemLog(value = "定时任务", method = "立即执行")
    @CacheEvict(cacheNames = "quartz", allEntries = true)
    public SaResult execute(@PathVariable("id") Long id) throws Exception {
        quartzService.execute(id);
        return SaResult.ok();
    }
}